package game.objects;
import physics.Body;
import physics.effects.Explosion;
import editors.objectedit.LoadObject;
import sound.main.Sound;
import tools.Floatmath;
import tools.Point;
import game.Game;
import game.engine.Empty;
import game.engine.GSync;
import game.logic.TimeActive;
import graphics.effects.GEExplosion;
import graphics.effects.GEFire;
public class GORocket extends TimeActive {
	private static float DELETEAFTER = 2.1f;
	private static float JETPOWER = 1800;
	private static float JETTIME = 3;
	Body body;
	private GEFire fire;
	private Sound boostsound;
	private Sound explosion;
	
	public GORocket(Game g, Point pos, float angle) {
		super(g, pos, angle, -1);
		boostsound = new Sound("boost.wav");
		boostsound.setLoop(true);
		explosion = new Sound("explosion.wav");
		explosion.setPitch(1f);
		explosion.setVolume(10);
		
	}
	@Override
	public void handle() {
		if (game.server) {
			if (lifetime == -1 && body != null && body.numCollidingWith() != 0) {
				lifetime = DELETEAFTER;
				this.addGraphicsObject(new GEExplosion(body.pos, 200), new GSync());
				Explosion expl = new Explosion(body.pos, 300, 300);
				game.engine.world.applyEffect(expl);
				this.remBodyWithGraphics(body);
				boostsound.pause();
				explosion.setPos(body.pos);
				explosion.play();
			}
		}
		if (this.getLifetime() == 1 && this.getAbsolutLifetime() < JETTIME && body != null) {
			body.applyForce(new Point(0, 1).rotate(body.apos + Floatmath.PIHALF).mul(-JETPOWER),body.pos.add(new Point(1,0).rotate(body.apos).mul(30)));
			fire.addLine(new Point(0, 1).rotate(body.apos + Floatmath.PIHALF).mul(100), 3);
			boostsound.setPos(fire.node.pos);
		}else if(this.getLifetime() == 1 && this.getAbsolutLifetime() > JETTIME && body != null){
			boostsound.pause();
			if(Math.random() < 0.5) fire.add(new Point(0, 1).rotate(body.apos + Floatmath.PIHALF).mul(10), 1);
		}
	}
	public void initialize(Point pos, float angle) {
		super.initialize(pos, angle);
		LoadObject.load("rocket", this, pos);
		body =  this.getBodyByName("body");
		body.apos = angle;
		body.mass = 2f;
		body.applyImpulse(new Point(0, 1).rotate(angle + Floatmath.PIHALF).mul(-2000));
		Empty firespot = (Empty) this.getEmptyByName("fire");
		fire = new GEFire(firespot.node.pos);
		boostsound.play();		
		boostsound.setPos(firespot.node.pos);
		this.addGraphicsObject(fire, new GSync(body, firespot.node.pos.sub(new Point(body.pos)), 0));
	}
	public void initialize(Point pos) {
		super.initialize(pos);
		LoadObject.load("rocket", this, pos);
		body =  this.getBodyByName("body");
		body.mass = 2f;		
		Empty firespot = (Empty) this.getEmptyByName("fire");
		fire = new GEFire(firespot.node.pos);
		boostsound.play();		
		boostsound.setPos(firespot.node.pos);
		this.addGraphicsObject(fire, new GSync(body, firespot.node.pos.sub(new Point(body.pos)), 0));
	}
}
